<template>
    <div class="rules-container">
        <h2>积分规则设置</h2>
        <!-- 搜索区域 -->
        <div class="search-area">
            <div class="search-item">
                <span class="label">群:</span>
                <el-select v-model="searchForm.groupId" placeholder="请选择要操作的群" class="search-input"
                    @change="fetchRules">
                    <el-option v-for="group in groupList" :key="group.groupId" :label="group.name"
                        :value="group.groupId" :disabled="group.status === '禁用' || group.botStatus !== '正常'" />
                </el-select>
            </div>
            <el-button type="primary" :icon="Search" class="search-btn" @click="fetchRules">查找</el-button>
        </div>

        <!-- 规则列表 -->
        <div class="rule-list" v-loading="loading">
            <!-- 发言增加积分规则 -->
            <el-card class="rule-card">
                <div class="rule-header">
                    <div class="rule-title">发言增加积分</div>
                    <el-switch v-model="rules.message.enabled" @change="() => handleRuleChange('message')" />
                </div>
                <div class="rule-content">
                    <div class="rule-desc">
                        {{ rules.message.enabled ? `群成员每次发言将增加 ${rules.message.points} 积分` : '规则已禁用' }}
                    </div>
                    <div class="rule-settings" v-if="rules.message.enabled">
                        <div class="points-setting">
                            <span class="points-label">积分值:</span>
                            <div class="points-controls">
                                <el-button :icon="Minus" @click="decreasePoints('message')"
                                    :disabled="rules.message.points <= 0" />
                                <span class="points-value">{{ rules.message.points }}</span>
                                <el-button :icon="Plus" @click="increasePoints('message')" />
                            </div>
                        </div>
                    </div>
                </div>
            </el-card>

            <!-- 邀请增加积分规则 -->
            <el-card class="rule-card">
                <div class="rule-header">
                    <div class="rule-title">邀请增加积分</div>
                    <el-switch v-model="rules.invite.enabled" @change="() => handleRuleChange('invite')" />
                </div>
                <div class="rule-content">
                    <div class="rule-desc">
                        {{ rules.invite.enabled ? `群成员每邀请一人入群将增加 ${rules.invite.points} 积分` : '规则已禁用' }}
                    </div>
                    <div class="rule-settings" v-if="rules.invite.enabled">
                        <div class="points-setting">
                            <span class="points-label">积分值:</span>
                            <div class="points-controls">
                                <el-button :icon="Minus" @click="decreasePoints('invite')"
                                    :disabled="rules.invite.points <= 0" />
                                <span class="points-value">{{ rules.invite.points }}</span>
                                <el-button :icon="Plus" @click="increasePoints('invite')" />
                            </div>
                        </div>
                    </div>
                </div>
            </el-card>

            <!-- 每日签到规则 -->
            <el-card class="rule-card">
                <div class="rule-header">
                    <div class="rule-title">每日签到</div>
                    <el-switch v-model="rules.checkin.enabled" @change="() => handleRuleChange('checkin')" />
                </div>
                <div class="rule-content">
                    <div class="rule-desc">
                        {{ rules.checkin.enabled ? `群成员每日签到将增加 ${rules.checkin.points} 积分` : '规则已禁用' }}
                    </div>
                    <div class="rule-settings" v-if="rules.checkin.enabled">
                        <div class="points-setting">
                            <span class="points-label">积分值:</span>
                            <div class="points-controls">
                                <el-button :icon="Minus" @click="decreasePoints('checkin')"
                                    :disabled="rules.checkin.points <= 0" />
                                <span class="points-value">{{ rules.checkin.points }}</span>
                                <el-button :icon="Plus" @click="increasePoints('checkin')" />
                            </div>
                        </div>
                    </div>
                </div>
            </el-card>

            <!-- 每日积分上限规则 -->
            <el-card class="rule-card">
                <div class="rule-header">
                    <div class="rule-title">每日积分上限</div>
                    <el-switch v-model="rules.daily_limit.enabled" @change="() => handleRuleChange('daily_limit')" />
                </div>
                <div class="rule-content">
                    <div class="rule-desc">
                        {{ rules.daily_limit.enabled ?
                            `群成员每日最多获得 ${rules.daily_limit.points} 积分（北京时间每日0点重置）` :
                            '规则已禁用' }}
                    </div>
                    <div class="rule-settings" v-if="rules.daily_limit.enabled">
                        <div class="points-setting">
                            <span class="points-label">积分值:</span>
                            <div class="points-controls">
                                <el-button :icon="Minus" @click="decreasePoints('daily_limit')"
                                    :disabled="rules.daily_limit.points <= 0" />
                                <span class="points-value">{{ rules.daily_limit.points }}</span>
                                <el-button :icon="Plus" @click="increasePoints('daily_limit')" />
                            </div>
                        </div>
                    </div>
                </div>
            </el-card>

            <!-- 每日积分清零规则 -->
            <el-card class="rule-card">
                <div class="rule-header">
                    <div class="rule-title">每日积分清零</div>
                    <el-switch v-model="rules.reset.enabled" @change="() => handleRuleChange('reset')" />
                </div>
                <div class="rule-content">
                    <div class="rule-desc">
                        {{ rules.reset.enabled ? '每天0点自动清零所有成员积分' : '规则已禁用' }}
                    </div>
                </div>
            </el-card>

            <!-- 保存按钮 -->
            <div class="action-bar">
                <el-button type="primary" @click="saveRules" :loading="saving">保存设置</el-button>
            </div>
        </div>
    </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { Search, Plus, Minus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { getGroups } from '../../../api/group'
import { getPointRules, updatePointRules } from '../../../api/pointRules'

export default {
    setup() {
        const searchForm = reactive({
            groupId: ''
        })
        const groupList = ref([])
        const loading = ref(false)
        const saving = ref(false)

        // 积分规则
        const rules = reactive({
            message: {
                enabled: false,
                points: 1,
                action: 'message'
            },
            invite: {
                enabled: false,
                points: 5,
                action: 'invite'
            },
            checkin: {
                enabled: false,
                points: 1,
                action: 'checkin'
            },
            reset: {
                enabled: false,
                points: 0,
                action: 'reset'
            },
            daily_limit: {
                enabled: false,
                points: 0,
                action: 'daily_limit'
            }
        })

        // 获取群组列表
        const fetchGroups = async () => {
            try {
                const res = await getGroups()
                if (res.data.success) {
                    groupList.value = res.data.data.filter(group => group.status === '启用' && group.botStatus === '正常')

                    if (groupList.value.length > 0 && !searchForm.groupId) {
                        searchForm.groupId = groupList.value[0].groupId
                        fetchRules()
                    }
                } else {
                    ElMessage.error(res.data.message || '获取群组失败')
                }
            } catch (error) {
                console.error('获取群组错误:', error)
                ElMessage.error('获取群组列表失败，请稍后重试')
            }
        }

        // 获取积分规则
        const fetchRules = async () => {
            if (!searchForm.groupId) {
                ElMessage.warning('请先选择群组')
                return
            }

            loading.value = true
            try {
                const res = await getPointRules(searchForm.groupId)
                console.log('获取到的积分规则:', res.data);
                
                if (res.data.success) {
                    const fetchedRules = res.data.data || []

                    // 初始化规则
                    rules.message.enabled = false
                    rules.invite.enabled = false
                    rules.checkin.enabled = false
                    rules.reset.enabled = false
                    rules.daily_limit.enabled = false

                    // 设置获取到的规则
                    fetchedRules.forEach(rule => {
                        if (rule.action === 'message' && rules.message) {
                            rules.message.enabled = rule.enabled
                            rules.message.points = Math.max(0, rule.points)
                        }
                        else if (rule.action === 'invite' && rules.invite) {
                            rules.invite.enabled = rule.enabled
                            rules.invite.points = Math.max(0, rule.points)
                        }
                        else if (rule.action === 'checkin' && rules.checkin) {
                            rules.checkin.enabled = rule.enabled
                            rules.checkin.points = Math.max(0, rule.points)
                        }
                        else if (rule.action === 'signin' && rules.checkin) {
                            // 如果找到signin规则，也更新checkin规则
                            rules.checkin.enabled = rule.enabled
                            rules.checkin.points = Math.max(0, rule.points)
                        }
                        else if (rule.action === 'reset' && rules.reset) {
                            rules.reset.enabled = rule.enabled
                        }
                        else if (rule.action === 'daily_limit' && rules.daily_limit) {
                            rules.daily_limit.enabled = rule.enabled
                            rules.daily_limit.points = Math.max(0, rule.points)
                        }
                    })
                } else {
                    ElMessage.error(res.data.message || '获取规则失败')
                }
            } catch (error) {
                console.error('获取规则错误:', error)
                ElMessage.error('获取规则失败，请稍后重试')
            } finally {
                loading.value = false
            }
        }

        // 处理规则变更
        const handleRuleChange = (ruleType) => {
            console.log(`${ruleType} 规则状态变更为: ${rules[ruleType].enabled}`)
        }

        // 增加积分值
        const increasePoints = (ruleType) => {
            rules[ruleType].points++
        }

        // 减少积分值
        const decreasePoints = (ruleType) => {
            if (rules[ruleType].points > 0) {
                rules[ruleType].points--
            }
        }

        // 保存规则
        const saveRules = async () => {
            if (!searchForm.groupId) {
                ElMessage.warning('请先选择群组')
                return
            }

            saving.value = true
            try {
                const ruleData = {
                    groupId: searchForm.groupId,
                    rules: [
                        {
                            action: 'message',
                            enabled: rules.message.enabled,
                            points: rules.message.points
                        },
                        {
                            action: 'invite',
                            enabled: rules.invite.enabled,
                            points: rules.invite.points
                        },
                        {
                            action: 'checkin',
                            enabled: rules.checkin.enabled,
                            points: rules.checkin.points
                        },
                        // 添加signin规则，与checkin保持一致
                        {
                            action: 'signin',
                            enabled: rules.checkin.enabled,
                            points: rules.checkin.points,
                            description: '每日签到积分'
                        },
                        {
                            action: 'reset',
                            enabled: rules.reset.enabled,
                            points: 0
                        },
                        {
                            action: 'daily_limit',
                            enabled: rules.daily_limit.enabled,
                            points: rules.daily_limit.points
                        }
                    ]
                }

                console.log('保存积分规则数据:', JSON.stringify(ruleData));
                const res = await updatePointRules(ruleData)
                if (res.data.success) {
                    ElMessage.success('规则保存成功')
                } else {
                    ElMessage.error(res.data.message || '规则保存失败')
                }
            } catch (error) {
                console.error('保存规则错误:', error)
                ElMessage.error('规则保存失败，请稍后重试')
            } finally {
                saving.value = false
            }
        }

        onMounted(() => {
            fetchGroups()
        })

        return {
            searchForm,
            groupList,
            rules,
            loading,
            saving,
            Search,
            Plus,
            Minus,
            fetchGroups,
            fetchRules,
            handleRuleChange,
            increasePoints,
            decreasePoints,
            saveRules
        }
    }
}
</script>

<style scoped>
.rules-container {
    padding: 20px;
}

h2 {
    font-size: 20px;
    font-weight: 500;
    margin-bottom: 20px;
    text-align: left;
}

.search-area {
    background-color: #fff;
    padding: 16px;
    border-radius: 4px;
    margin-bottom: 16px;
    display: flex;
    align-items: center;
    gap: 15px;
    flex-wrap: wrap;
    box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.search-item {
    display: flex;
    align-items: center;
}

.label {
    font-size: 13px;
    color: #606266;
    margin-right: 8px;
}

.search-input {
    width: 180px;
}

.search-btn {
    height: 32px;
    padding: 0 15px;
    font-size: 13px;
}

.rule-list {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 16px;
    margin-bottom: 20px;
}

.rule-card {
    border-radius: 4px;
}

.rule-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
}

.rule-title {
    font-weight: bold;
    font-size: 16px;
}

.rule-content {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
}

.rule-desc {
    font-size: 13px;
    color: #606266;
    line-height: 1.5;
}

.rule-settings {
    padding: 5px 0;
}

.points-setting {
    display: flex;
    align-items: center;
}

.points-label {
    width: 60px;
    font-size: 13px;
    color: #606266;
}

.points-controls {
    display: flex;
    align-items: center;
}

.points-value {
    margin: 0 15px;
    min-width: 20px;
    text-align: center;
    font-size: 15px;
    color: #303133;
    line-height: 1.5;
}

.action-bar {
    display: flex;
    justify-content: center;
    margin-top: 20px;
}

:deep(.el-button--primary) {
    --el-button-bg-color: #1890ff;
    --el-button-border-color: #1890ff;
    --el-button-hover-bg-color: #40a9ff;
    --el-button-hover-border-color: #40a9ff;
}

:deep(.el-input__inner) {
    height: 32px;
}
</style>